<?php namespace Core\Myapp\Helper\Admin\Form;


class Form extends \Core\Myapp\Zobero
{
    protected $_attributes = array();
    protected $_groups = array();
    protected $_data = array();

    protected function formOpen()
    {
        $attributes = '';
        foreach($this->_attributes as $name=>$value) {
            $attributes .=" name='{$value}'";
        }
        return "<form {$attributes}>";
    }

    public function setAttribute($name, $value)
    {
        $this->_attributes[$name] = $value;
        return $this;
    }

    public function setData($data)
    {
        $this->_data = $data;
        return $this;
    }
    public function getData()
    {
        return $this->_data;
    }
    public function getFieldValue($name)
    {
        return isset($this->_data[$name]) ? $this->_data[$name] : null;
    }
    public function addGroup($id, $title, $sortOrder)
    {
        $this->_groups[$id] = new \Core\Myapp\Helper\Admin\Form\Group\Group($id, $title, $sortOrder);
        return $this;
    }

    public function getGroups()
    {
        return $this->_groups;
        return usort($this->_groups, array($this, "sortHelper"));;
    }

    public function getGroup($id)
    {
        return $this->_groups[$id];
    }

    protected function sortHelper($a, $b)
    {
        $aOrder = (int)$a->getSortOrder();
        $bOrder = (int)$b->getSortOrder();
        if ($aOrder == $bOrder) {
            return 0;
        }
        return ($aOrder < $bOrder) ? -1 : 1;
    }

    public function render()
    {
        ob_start();
        echo $this->formOpen();
        foreach($this->getGroups() as $group) {
            echo $group->render();
        }
        echo $this->formClose();
        $html = ob_get_clean();
        return $html;
    }

    protected function formClose()
    {
        return '</form>';
    }

}